import { NextRequest, NextResponse } from 'next/server';

// 模拟数据库
let items = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
];

// 获取所有items
export async function GET(request: NextRequest) {
  return NextResponse.json(items);
}

// 创建一个新的item
export async function POST(request: NextRequest) {
  const { name } = await request.json();
  const newItem = { id: items.length + 1, name };
  items.push(newItem);
  return NextResponse.json(newItem, { status: 201 });
}

// 更新一个item
export async function PUT(request: NextRequest) {
  const { id, name } = await request.json();
  const itemIndex = items.findIndex(item => item.id === id);
  if (itemIndex !== -1) {
    items[itemIndex] = { id, name };
    return NextResponse.json(items[itemIndex]);
  }
  return NextResponse.json({ error: 'Item not found' }, { status: 404 });
}

// 删除一个item
export async function DELETE(request: NextRequest) {
  const { id } = await request.json();
  const itemIndex = items.findIndex(item => item.id === id);
  if (itemIndex !== -1) {
    const deletedItem = items.splice(itemIndex, 1);
    return NextResponse.json(deletedItem);
  }
  return NextResponse.json({ error: 'Item not found' }, { status: 404 });
}